var mongoose = require('mongoose');


var UserSchema = new mongoose.Schema({
    name: {
        unique: true,
        type: String
    },
    password: String,
    meta: {
        crateAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    }
});

UserSchema.pre('save', function (next) {
    if(this.isNew){
        this.meta.crateAt = this.meta.updateAt = Date.now();
    }else{
        this.meta.updateAt = Date.now();
    }
    next()
});

UserSchema.static = {
    fetch:function(cb){
        return this.find({}).sort('meta.updateAt');
        exec(cb);
    },
    findById:function(id, cb){
        return this.findOne({_id:id});
        exec(cb);
    }
}

module.exports = UserSchema;